package org.springframework.license.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.license.exception.LicenseException;
import org.springframework.license.validate.LicenseVerify;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.alibaba.fastjson.JSONObject;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @Title LicenseInterceptor
 * @Author zhijun.Guo
 * @Email tiankong061015@163.com
 * @Time 2024/9/3 00:31
 * @Description
 */
@Slf4j
public class LicenseInterceptor implements HandlerInterceptor {

    /**
     * 跳过授权验证的URL前缀
     */
    private static final Set<String> UN_VALIDATE_REQUEST_PREFIX = new HashSet<>();

    static {
        UN_VALIDATE_REQUEST_PREFIX.add("/license");
        UN_VALIDATE_REQUEST_PREFIX.add("/dist");
        UN_VALIDATE_REQUEST_PREFIX.add("/pages");
        UN_VALIDATE_REQUEST_PREFIX.add("/components");
        UN_VALIDATE_REQUEST_PREFIX.add("/error");
        UN_VALIDATE_REQUEST_PREFIX.add("/serviceConfigure");
        UN_VALIDATE_REQUEST_PREFIX.add("/time");
        UN_VALIDATE_REQUEST_PREFIX.add("/computer/information");
    }

    private Boolean validateUriPrefix(String uri){
        if("/".equals(uri)){return true;}
        if(uri.endsWith(".html") || uri.endsWith(".js") || uri.endsWith(".css")){return true;}
        for (String prefix : UN_VALIDATE_REQUEST_PREFIX) {
            if(uri.startsWith(prefix)){return true;}
        }
        return false;
    }

    /**
     * 对外提供跳过授权注册的URL, 每次启动服务都需要注册
     * @param uri url
     */
    public static void registerUnValidateUriPrefix(String... uri){
        UN_VALIDATE_REQUEST_PREFIX.addAll(Arrays.asList(uri));
    }

    /**
     * 证书无效,则拦截所有请求
     * @param request   request
     * @param response  response
     * @param handler   handler
     * @return  return
     * @throws Exception 异常信息
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(this.validateUriPrefix(request.getRequestURI())) return true;
        try {
            LicenseVerify licenseVerify = new LicenseVerify();
            licenseVerify.validate();
            return true;
        }catch (Exception e){
            throw new LicenseException(99099, "您的证书无效或授权已过期，请核查服务器是否取得授权或重新申请证书！");
        }
    }
}
